<template>
  <div id="app" class="skStudentTable">
    <a-table :loading="loading" :pagination="false" :columns="columns" :data-source="dataSource" rowKey="studentId" bordered :scroll="{x:2000,y:800}"></a-table>
  </div>
</template>
<script>
import { getAction } from '@/api/manage'
import { skStudentList } from "@/api/management.js";
export default {
  name: 'skStudentTable',
  data() {
    return {
      url: {
        list: 'health/skSportRecord/getSprotStatistical'
      },
      loading:false,
      dataForm: {},
      dataDate: '',
      columns:[],
      dataSource:[],
      studentList:[]
    }
  },
  props:["detailName", "dateType", "rateType"],
  components: {},

  filters: {},

  computed: {},
  
  created() {
    this.dataDate = this.$skCommon.getDate(1);
  },
  
  activated() {},
  
  mounted() {},
  
  methods: {
    // 获取学生具体信息
    async getStudentData(dataForm){     
      this.dataForm = dataForm;
      console.log(this.dataForm);
      this.setColumns();
      await this.getStudentList(dataForm);
      await this.handleData(dataForm);
    },
    getStudentList(dataForm){
      const params = {
        classId:dataForm.classId
      }
      skStudentList(params).then((res)=>{
        if(res.success){
          this.studentList = res.result;
        } else {
          this.$message.warning(res.message);
        }
      }).catch((error)=>{
        console.error(error);
      })
    },
    handleData(dataForm){
      const semesterId = dataForm.semesterId ? dataForm.semesterId : dataForm.semesterHistoryId
      const params = {
        statisticalScope: 'student',
        timeScope: dataForm.dateType == 'sem' || dataForm.dateType == 'historySem' ? semesterId : dataForm.dateType,
        classId: dataForm.classId ? dataForm.classId : undefined,
        areaType: dataForm.areaType ? dataForm.areaType : undefined
      }
  
      this.loading = true;
      getAction(this.url.list,params).then((res)=>{
        if(res.success){
          this.dataSource = [];
          if(res.result.length > 0) {
            let studentList = this.unique(res.result.map(item => (
              {
                classId: item.classId,
                className: item.className,
                classType: item.classType,
                studentId: item.studentId,
                studentName: item.studentName
              }
            )), 'studentId');
            console.log('studentList', studentList);
            this.studentList.forEach(el => {
              let stuItem = {
                classId: el.classId,
                className: el.className,
                classType: el.classTypeName,
                studentId: el.id,
                studentName: el.name
              }
              const stuData = res.result.filter(item => {
                return item.studentId == el.id
              })
              
              let totalAmountSum = 0;
              let totalStepNumberSum = 0;
              let totalDurationSum = 0;
              for(let rowIndex = 0; rowIndex < this.dataColumns.length; rowIndex++){
                const rowString = this.dataColumns[rowIndex].toString()
  
                if (this.dataForm.dateType == 'sem' || this.dataForm.dateType == 'historySem') {
                  const monthData = stuData.find(item => item.month == rowString);
                  if(monthData){
                    totalAmountSum += monthData.totalAmount;
                    totalStepNumberSum += monthData.totalStepNumber;
                    totalDurationSum += monthData.totalDuration;
                    stuItem['totalAmount' + rowString] = monthData.totalAmount.toFixed(2);
                    stuItem['totalStepNumber' + rowString] = monthData.totalStepNumber.toFixed(2);
                    stuItem['totalDuration' + rowString] = monthData.totalDuration.toFixed(2);
                  }
                }else {
                  const monthData = stuData.find(item => item.statisticalDate.substring(5) == rowString);
                  if(monthData){
                    totalAmountSum += monthData.totalAmount;
                    totalStepNumberSum += monthData.totalStepNumber;
                    totalDurationSum += monthData.totalDuration;
                    stuItem['totalAmount' + rowString] = monthData.totalAmount.toFixed(2);
                    stuItem['totalStepNumber' + rowString] = monthData.totalStepNumber.toFixed(2);
                    stuItem['totalDuration' + rowString] = monthData.totalDuration.toFixed(2);
                  }
                }
              }
              stuItem['totalAmountAvg'] = stuData.length == 0 ? '-' : (totalAmountSum / stuData.length).toFixed(2);
              stuItem['totalStepNumberAvg'] = stuData.length == 0 ? '-' : (totalStepNumberSum / stuData.length).toFixed(2);
              stuItem['totalDurationAvg'] = stuData.length == 0 ? '-' : (totalDurationSum / stuData.length).toFixed(2);
              this.dataSource.push(stuItem);
            })
          }
          this.loading = false;
        } else {
          this.$message.warning(res.message);
        }
      }).catch((error)=>{
        console.error(error);
        this.loading = false;
      })
    },
    unique(newarr, key) {
      const res = new Map();
      return newarr.filter((arr) => !res.has(arr[key]) && res.set(arr[key], 1));
    },
    // 表头
    setColumns(){
      this.columns = [
        {
          title: '年级',
          align: 'center',
          fixed: 'left',
          width: 80,
          dataIndex: 'classType'
        },
        {
          title: '班级',
          align: 'center',
          dataIndex: 'className',
          fixed: 'left',
          width: 80,
        },
        {
          title: '学生',
          align: 'center',
          dataIndex: 'studentName',
          fixed: 'left',
          width: 100,
        }
      ];

      let totalTitle = '月'
      if (this.dataForm.dateType == 'week') {
        totalTitle = '周'
        this.dataColumns = this.$skCommon.getCurrentWeekDays();
      } else if (this.dataForm.dateType == 'sem' || this.dataForm.dateType == 'historySem') {
        totalTitle = '学期'
        const semester = this.dataForm.semester;
        this.dataColumns = this.$skCommon.getMonths(semester.startDate, semester.endDate, 'yyyy-MM');
      } else {
        totalTitle = '月'
        this.dataColumns = this.$skCommon.getCurrentMonthDays();
      }
      console.log('days', this.dataColumns);
      for(let rowIndex = 0; rowIndex < this.dataColumns.length; rowIndex++){
        const rowString = this.dataColumns[rowIndex].toString()
        this.columns.push(
          {
            title: rowString,
            align: 'center',
            children: [
              {
                title: '运动量',
                align: 'center',
                dataIndex: 'totalAmount'+rowString,
                key: 'totalAmount'+rowString,
                width: 120,
                customRender: function(text) {
                  return text || '-'
                }
              },
              {
                title: '步数',
                align: 'center',
                dataIndex: 'totalStepNumber'+rowString,
                key: 'totalStepNumber'+rowString,
                width: 120,
                customRender: function(text) {
                  return text || '-'
                }
              },
              {
                title: '运动时长(分钟)',
                align: 'center',
                dataIndex: 'totalDuration'+rowString,
                key: 'totalDuration'+rowString,
                width: 140,
                customRender: function(text) {
                  return text || '-'
                }
              },
            ],
          },
        )
      }
      this.columns.push(
        {
          title: totalTitle + '平均',
          align: 'center',
          children: [
            {
              title: '运动量',
              align: 'center',
              dataIndex: 'totalAmountAvg',
              key: 'totalAmountAvg',
              width: 140,
              customRender: function(text) {
                return text || '-'
              }
            },
            {
              title: '步数',
              align: 'center',
              dataIndex: 'totalStepNumberAvg',
              key: 'totalStepNumberAvg',
              width: 140,
              customRender: function(text) {
                return text || '-'
              }
            },
            {
              title: '运动时长(分钟)',
              align: 'center',
              dataIndex: 'totalDurationAvg',
              key: 'totalDurationAvg',
              width: 140,
              customRender: function(text) {
                return text || '-'
              }
            },
          ],
        },
      )
    },
  }
}
</script>
<style scoped>
/* @import url(); 引入css类 */
</style>
